package config

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"gopkg.in/yaml.v2"
)

// DB 数据库指针
var DB *sql.DB

type (
	// DBConfig 数据库配置
	DBConfig struct {
		// Mysql mysql配置
		Mysql struct {
			Host     string `yaml:"host"`
			Port     string `yaml:"port"`
			UserName string `yaml:"username"`
			Password string `yaml:"password"`
			DataBase string `yaml:"database"`
			Charset  string `yaml:"charset"`
		}
	}
)

// DBinit 数据库初始化
func init() {
	var err error
	file, err := os.Open("../config/db.yaml")
	defer file.Close()
	checkError(err, "打开数据库配置文件失败")

	bytes, err := ioutil.ReadAll(file)
	checkError(err, "读取数据库配置文件失败")

	var config DBConfig
	err = yaml.Unmarshal(bytes, &config)
	checkError(err, "解析数据库配置文件失败")

	info := config.Mysql

	connURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local&timeout=1000ms", info.UserName, info.Password, info.Host, info.Port, info.DataBase, info.Charset)
	log.Printf("数据库连接地址:%s\n", connURL)

	DB, err = sql.Open("mysql", connURL)

	checkError(err, "打开数据库连接失败")

	log.Println("数据库初始化完成...")
}

func checkError(err error, notice string) {
	if err != nil {
		log.Fatal("notice\n", err)
		panic(err)
	}
}
